<?php

namespace haibao\erp\data\product;

use \haibao\erp\model\filter\product\Product as ProductFilter; 
use \haibao\erp\model\data\product\ProductRelCategoryProperty as ProductRelCategoryPropertyModelData;


class Product extends \haibao\erp\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\erp\model\data\product\Product');
	}
	
	public function addProduct($model,$propertyVaAr){
        self::beginTranscation();
        try{
            parent::add($model);

            if($model->ProductContentInfo){
                foreach($model->ProductContentInfo as $data){
                    $data->ProductId = $model->Id;
                    parent::add($data);
                }
            }
            if (!empty($propertyVaAr)) $this->dealProductRelCategoryProperty($model->Id,$propertyVaAr);
            
        }catch (\Exception $e){
            $this->rollback();
        }
        $this->endTranscation();
	}
	
	
	public function updateProduct($model,$propertyVaAr){

		self::beginTranscation();
		  $productModel = $this->packEditProduct($model);
		try{
			parent::updateById(intval($model->Id), $model);

			$this->dealProductContentInfo($model->Id, $model->ProductContentInfo);
            if (!empty($propertyVaAr)) $this->dealProductRelCategoryProperty(intval($model->Id),$propertyVaAr);
			
		}catch (\Exception $e){
		    echo $e->getMessage();
			$this->rollback();
		}
		$this->endTranscation();
	}

	private function dealProductContentInfo($productId, $productContentInfo){
        $data = new ProductContentInfo();
        foreach($productContentInfo as $dataType=>$item){

            switch ($dataType) {
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_PRICE:
                    if ($item) $data->update($item['updateData'], $item['whereCondition']);

                    break;
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_IMAGE_PRO:
                    if($item['del']) $data->remove($item['del']);
                    if($item['add']) $data->addAll($item['add']);
                    break;
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_DESC;
                    if($item['update']) $data->update($item['update']['updateData'],$item['update']['whereCondition']);
                    if($item['add']) parent::add($item['add']);
                    break;
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_DETAIL;
                    if($item['update']) $data->update($item['update']['updateData'],$item['update']['whereCondition']);
                    if($item['add']) parent::add($item['add']);

                    break;
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_CATEGORY_INFO;
                    if($item) $data->update($item['updateData'],$item['whereCondition']);
                    break;
                case \haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_RETURNS;
                    if($item['update']) $data->update($item['update']['updateData'],$item['update']['whereCondition']);
                    if($item['add']) parent::add($item['add']);
                    break;

            }
        }

    }
    private function dealProductRelCategoryProperty($productId,$propertyVaAr){
        $propertyList = array();
        $row = array();
        $productRelCategoryPropertyData = new \haibao\erp\data\product\ProductRelCategoryProperty();
        
        $sql = 'select * from ProductRelCategoryProperty where ProductId=%s';
        $propertyList = $this->query($sql,array($productId));
        while ($propertyList->fetch_assoc()){
            array_push($row, $propertyList->getData('Id'));
        }
     
        if($row){
           $delSql = 'DELETE FROM ProductRelCategoryProperty WHERE ProductId=%s';
           $this->query($delSql,array(intval($productId)));
        }
      
        $productRelCategoryPropertyModelData = new ProductRelCategoryPropertyModelData();
        
        $productRelCategoryPropertyModelData->ProductId = $productId;
        $productRelCategoryPropertyModelData->CreateTime = new \DateTime();
        foreach ($propertyVaAr as $k=>$v){
            $productRelCategoryPropertyModelData->PropertyId = $v['PropertyId'];
            $productRelCategoryPropertyModelData->PropertyName = $v['PropertyName'];
            $productRelCategoryPropertyModelData->PropertyValue = $v['PropertyValue'];
            $productRelCategoryPropertyModelData->ValueType = $v['ValueType'];
            
            $productRelCategoryPropertyData->add($productRelCategoryPropertyModelData);
        }
    }
    
	private function packEditProduct($model){
	    $productFilter = new ProductFilter();
	    $productFilter = array(
	        ProductFilter::CONDITION_FIELD_NAME_BRAND_ID =>$model->BrandId,
	        ProductFilter::CONDITION_FIELD_NAME_CATEGORY_ID =>$model->CategoryId,
	        ProductFilter::CONDITION_FIELD_NAME_PRODUCT_NAME =>$model->ProductName,
	        ProductFilter::CONDITION_FIELD_NAME_TITLE =>$model->Title,
	        ProductFilter::CONDITION_FIELD_NAME_TOTAL_STOCK =>$model->TotalStock,
	        ProductFilter::CONDITION_FIELD_NAME_STATUS =>$model->Status,
	        ProductFilter::CONDITION_FIELD_NAME_UPDATETIME =>$model->UpdateTime,
	        ProductFilter::CONDITION_FIELD_NAME_CREATETIME =>$model->CreateTime,
	        ProductFilter::CONDITION_FIELD_NAME_CREATE_BY =>$model->CreateBy,
	        ProductFilter::CONDITION_FIELD_NAME_UPDATE_BY =>$model->UpdateBy,
	    );
	    return $productFilter;
	}

    public function addProductBySpider($model){
        self::beginTranscation();
        try{
            parent::add($model);

            if($model->ProductContentInfo){
                foreach($model->ProductContentInfo as $productInfo){
                    $productInfo->ProductId = $model->Id;
                }
                $this->addAll($model->ProductContentInfo);
            }
            if($model->ProductCategoryList){
            	foreach($model->ProductCategoryList as $productInfo){
            		$productInfo->ProductId = $model->Id;
            	}
            	$this->addAll($model->ProductCategoryList);
            }

        }catch (\Exception $e){
            $this->rollback();
        }
        $this->endTranscation();
    }

    public function checkProductIsExist($originUrl,$categoryId){

        $sql = 'select Id from Product where OriginUrl=%s and CategoryId = %s limit 1';
        return $this->query($sql, array($originUrl,$categoryId))->fetch_assoc();
    }

    public   function  getProductByProductIds($productIdArr,$dataType){

        $productIds=implode(',',$productIdArr);
        $str=preg_replace('/(\d+)/','%s',$productIds);
        if ($dataType){
            $sql='SELECT ProductId, ContentInfo, DataType FROM ProductContentInfo where ProductId in ('.$str.') and DataType=%d';
            array_push($productIdArr,$dataType);
        }
        else{
            $sql='SELECT ProductId, ContentInfo, DataType FROM ProductContentInfo where ProductId in ('.$str.')';
        }
        $result =$this->query($sql,$productIdArr);
        $list=array();
        while ($result->fetch_assoc()){
            if ($dataType){
                $list[$result->getData('ProductId')]=$result->getData('ContentInfo');
            }else{
                if (!isset($list[$result->getData('ProductId')])) $list[$result->getData('ProductId')]=array();
                $list[$result->getData('ProductId')][$result->getData('DataType')]=$result->getData('ContentInfo');
            }
        }
        return $list;

    }

    public function checkProductHasImage($productId,$imageId){

        $sql = 'select Id from ProductContentInfo where ProductId=%s and ContentInfo=%s and DataType=%s limit 1';
        return $this->query($sql, array($productId,$imageId,\haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_IMAGE_PRO))->fetch_assoc();
    }

    public function checkProductHasMapMisaki($misakiProductId){

        $sql = 'select Id from ProductContentInfo where ContentInfo=%s and DataType=%s limit 1';
        return $this->query($sql, array($misakiProductId,\haibao\erp\model\data\product\ProductContentInfo::DATA_TYPE_MISAKI_PRODUCT_ID))->fetch_assoc();
    }

    public  function  prdocutForPrevAndNext($productId,$CategoryId){

        $list = array();
        $sql = 'select Id from Product where Id < '.$productId.' and CategoryId='.$CategoryId.' ORDER BY Id DESC limit 1';
         $lastId = $this->query($sql)->fetch_assoc();
        $sql = 'select Id from Product where Id > '.$productId.' and CategoryId='.$CategoryId.' order by Id asc limit 1';
        $nextId = $this->query($sql)->fetch_assoc();
        if ($lastId){
            $list['prev'] = $lastId['Id'];
        }
        if ($nextId){
            $list['next'] = $nextId['Id'];
        }
        return $list;
    }

}